// src/screens/CompleteProfileScreen.js
import React, { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, StyleSheet, Image, ScrollView, Alert, FlatList } from 'react-native';
import { useDispatch } from 'react-redux';
import api from '../services/api';
import { setUserInfo } from '../store/userSlice';

const CompleteProfileScreen = ({ navigation }) => {
  const [step, setStep] = useState(1); // 1: 同意条款, 2: 上传照片, 3: 填写基本信息, 4: 兴趣选择, 5: 关系目的, 6: 语言选择, 7: 母语选择, 8: 国籍选择
  const [nickname, setNickname] = useState('');
  const [gender, setGender] = useState('');
  const [birthday, setBirthday] = useState('');
  const [avatar, setAvatar] = useState(null);
  const [images, setImages] = useState([]);
  const [interests, setInterests] = useState([]);
  const [relationshipGoal, setRelationshipGoal] = useState('');
  const [languages, setLanguages] = useState([]);
  const [motherTongue, setMotherTongue] = useState('');
  const [nationality, setNationality] = useState('');
  const dispatch = useDispatch();

  // 兴趣选项
  const interestOptions = [
    '音乐', '电影', '旅行', '美食', '运动', '阅读', '游戏', '摄影', 
    '艺术', '科技', '时尚', '健身', '烹饪', '舞蹈', '户外', '宠物'
  ];

  // 关系目的选项
  const relationshipGoals = [
    '长期关系', '婚姻', '短期交往', '聊天交友', '寻找partner'
  ];

  // 语言选项
  const languageOptions = [
    '中文', 'English', '日本語', '한국어', 'Français', 'Español', 'Русский', 'العربية'
  ];

  // 国籍选项
  const nationalities = [
    '中国', '美国', '日本', '韩国', '法国', '西班牙', '俄罗斯', '沙特阿拉伯',
    '英国', '德国', '印度', '加拿大', '澳大利亚', '巴西', '墨西哥', '意大利'
  ];

  const nextStep = async () => {
    if (step === 1) {
      setStep(2);
    } else if (step === 2 && images.length >= 2) {
      setStep(3);
    } else if (step === 2 && images.length < 2) {
      Alert.alert('提示', '请至少上传2张照片');
    } else if (step === 3) {
      if (!nickname || !gender || !birthday) {
        Alert.alert('提示', '请填写完整的基本信息');
        return;
      }
      setStep(4);
    } else if (step === 4 && interests.length > 0) {
      setStep(5);
    } else if (step === 4 && interests.length === 0) {
      Alert.alert('提示', '请选择至少一个兴趣');
    } else if (step === 5 && relationshipGoal) {
      setStep(6);
    } else if (step === 5 && !relationshipGoal) {
      Alert.alert('提示', '请选择您的关系目的');
    } else if (step === 6 && languages.length > 0) {
      setStep(7);
    } else if (step === 6 && languages.length === 0) {
      Alert.alert('提示', '请选择至少一种语言');
    } else if (step === 7 && motherTongue) {
      setStep(8);
    } else if (step === 7 && !motherTongue) {
      Alert.alert('提示', '请选择您的母语');
    } else if (step === 8 && nationality) {
      // 提交所有资料
      try {
        const profileData = {
          nickname,
          gender,
          birthday,
          interests,
          relationshipGoal,
          languages,
          motherTongue,
          nationality,
        };
        
        // 调用API更新用户资料
        const response = await api.updateUserProfile(profileData);
        
        // 更新Redux中的用户信息
        dispatch(setUserInfo(response.data));
        
        // 跳转到主页
        navigation.replace('Main');
      } catch (error) {
        console.log('更新用户资料失败:', error);
        Alert.alert('错误', '更新用户资料失败，请稍后重试');
      }
    }
  };

  const prevStep = () => {
    if (step > 1) {
      setStep(step - 1);
    }
  };

  // 模拟图片选择函数
  const selectImage = () => {
    if (images.length < 6) {
      const newImage = { id: Date.now(), uri: `https://picsum.photos/200/300?random=${images.length}` };
      setImages([...images, newImage]);
    }
  };

  // 删除图片
  const removeImage = (id) => {
    setImages(images.filter(image => image.id !== id));
  };

  // 选择兴趣
  const toggleInterest = (interest) => {
    if (interests.includes(interest)) {
      setInterests(interests.filter(i => i !== interest));
    } else if (interests.length < 10) {
      setInterests([...interests, interest]);
    }
  };

  // 选择关系目的
  const selectRelationshipGoal = (goal) => {
    setRelationshipGoal(goal);
  };

  // 添加语言
  const toggleLanguage = (language) => {
    if (languages.includes(language)) {
      setLanguages(languages.filter(l => l !== language));
    } else {
      setLanguages([...languages, language]);
    }
  };

  // 选择母语和国籍
  const selectMotherTongue = (language) => {
    setMotherTongue(language);
  };

  const selectNationality = (country) => {
    setNationality(country);
  };

  return (
    <ScrollView contentContainerStyle={styles.container}>
      {/* 进度条 */}
      <View style={styles.progressBarContainer}>
        <View style={[styles.progressBar, { width: `${(step / 8) * 100}%` }]} />
      </View>
      
      <Text style={styles.stepText}>第 {step} 步 / 共 8 步</Text>

      {/* 步骤1: 同意条款 */}
      {step === 1 && (
        <View style={styles.stepContainer}>
          <Text style={styles.title}>你好！第一次使用 MEEFF 吗？</Text>
          <Text style={styles.subtitle}>请同意条款，以获得更充分的服务体验</Text>
          
          <View style={styles.agreementContainer}>
            <TouchableOpacity style={styles.checkbox}>
              <Text>✓</Text>
            </TouchableOpacity>
            <Text style={styles.agreementText}>我同意《用户协议》和《隐私政策》</Text>
          </View>
          
          <TouchableOpacity style={styles.primaryButton} onPress={nextStep}>
            <Text style={styles.buttonText}>继续</Text>
          </TouchableOpacity>
        </View>
      )}

      {/* 步骤2: 上传照片 */}
      {step === 2 && (
        <View style={styles.stepContainer}>
          <Text style={styles.title}>请上传个人资料图片</Text>
          <Text style={styles.subtitle}>至少需要上传2张照片</Text>
          
          <View style={styles.imageUploadContainer}>
            <TouchableOpacity style={styles.addImageBox} onPress={selectImage}>
              <Text style={styles.addImageText}>+</Text>
            </TouchableOpacity>
            
            {images.map((image) => (
              <View key={image.id} style={styles.imageContainer}>
                <Image source={{ uri: image.uri }} style={styles.uploadedImage} />
                <TouchableOpacity 
                  style={styles.removeImageButton} 
                  onPress={() => removeImage(image.id)}
                >
                  <Text style={styles.removeImageText}>✕</Text>
                </TouchableOpacity>
              </View>
            ))}
          </View>
          
          <View style={styles.buttonRow}>
            <TouchableOpacity style={styles.secondaryButton} onPress={prevStep}>
              <Text style={styles.buttonText}>上一步</Text>
            </TouchableOpacity>
            <TouchableOpacity 
              style={[styles.primaryButton, images.length < 2 && styles.disabledButton]} 
              onPress={nextStep}
              disabled={images.length < 2}
            >
              <Text style={styles.buttonText}>继续</Text>
            </TouchableOpacity>
          </View>
        </View>
      )}

      {/* 步骤3: 填写基本信息 */}
      {step === 3 && (
        <View style={styles.stepContainer}>
          <Text style={styles.title}>请填入基本信息</Text>
          
          <TextInput 
            placeholder="昵称" 
            value={nickname} 
            onChangeText={setNickname} 
            style={styles.input}
            maxLength={20}
          />
          
          <View style={styles.radioContainer}>
            <Text style={styles.radioLabel}>性别:</Text>
            <TouchableOpacity 
              style={[styles.radioButton, gender === 'male' && styles.selectedRadio]} 
              onPress={() => setGender('male')}
            >
              <Text>男</Text>
            </TouchableOpacity>
            <TouchableOpacity 
              style={[styles.radioButton, gender === 'female' && styles.selectedRadio]} 
              onPress={() => setGender('female')}
            >
              <Text>女</Text>
            </TouchableOpacity>
          </View>
          
          <TextInput 
            placeholder="生日 (YYYY-MM-DD)" 
            value={birthday} 
            onChangeText={setBirthday} 
            style={styles.input}
            keyboardType="numbers-and-punctuation"
            maxLength={10}
          />
          
          <View style={styles.buttonRow}>
            <TouchableOpacity style={styles.secondaryButton} onPress={prevStep}>
              <Text style={styles.buttonText}>上一步</Text>
            </TouchableOpacity>
            <TouchableOpacity 
              style={[styles.primaryButton, (!nickname || !gender || !birthday) && styles.disabledButton]} 
              onPress={nextStep}
              disabled={!nickname || !gender || !birthday}
            >
              <Text style={styles.buttonText}>继续</Text>
            </TouchableOpacity>
          </View>
        </View>
      )}

      {/* 步骤4: 选择兴趣 */}
      {step === 4 && (
        <View style={styles.stepContainer}>
          <Text style={styles.title}>选择你的兴趣</Text>
          <Text style={styles.subtitle}>最多可选择10个兴趣爱好</Text>
          
          <View style={styles.interestsContainer}>
            {interestOptions.map((interest, index) => (
              <TouchableOpacity 
                key={index}
                style={[styles.interestItem, interests.includes(interest) && styles.selectedInterest]}
                onPress={() => toggleInterest(interest)}
              >
                <Text style={[styles.interestText, interests.includes(interest) && styles.selectedInterestText]}>
                  {interest}
                </Text>
              </TouchableOpacity>
            ))}
          </View>
          
          <View style={styles.buttonRow}>
            <TouchableOpacity style={styles.secondaryButton} onPress={prevStep}>
              <Text style={styles.buttonText}>上一步</Text>
            </TouchableOpacity>
            <TouchableOpacity 
              style={[styles.primaryButton, interests.length === 0 && styles.disabledButton]} 
              onPress={nextStep}
              disabled={interests.length === 0}
            >
              <Text style={styles.buttonText}>继续</Text>
            </TouchableOpacity>
          </View>
        </View>
      )}

      {/* 步骤5: 选择关系目的 */}
      {step === 5 && (
        <View style={styles.stepContainer}>
          <Text style={styles.title}>你想寻找什么样的关系?</Text>
          <Text style={styles.subtitle}>请选择你的交友目的</Text>
          
          <View style={styles.optionsContainer}>
            {relationshipGoals.map((goal, index) => (
              <TouchableOpacity 
                key={index}
                style={[styles.optionItem, relationshipGoal === goal && styles.selectedOption]}
                onPress={() => selectRelationshipGoal(goal)}
              >
                <Text style={[styles.optionText, relationshipGoal === goal && styles.selectedOptionText]}>
                  {goal}
                </Text>
              </TouchableOpacity>
            ))}
          </View>
          
          <View style={styles.buttonRow}>
            <TouchableOpacity style={styles.secondaryButton} onPress={prevStep}>
              <Text style={styles.buttonText}>上一步</Text>
            </TouchableOpacity>
            <TouchableOpacity 
              style={[styles.primaryButton, !relationshipGoal && styles.disabledButton]} 
              onPress={nextStep}
              disabled={!relationshipGoal}
            >
              <Text style={styles.buttonText}>继续</Text>
            </TouchableOpacity>
          </View>
        </View>
      )}

      {/* 步骤6: 选择语言 */}
      {step === 6 && (
        <View style={styles.stepContainer}>
          <Text style={styles.title}>你感兴趣的语言</Text>
          <Text style={styles.subtitle}>可多选</Text>
          
          <View style={styles.optionsContainer}>
            {languageOptions.map((language, index) => (
              <TouchableOpacity 
                key={index}
                style={[styles.optionItem, languages.includes(language) && styles.selectedOption]}
                onPress={() => toggleLanguage(language)}
              >
                <Text style={[styles.optionText, languages.includes(language) && styles.selectedOptionText]}>
                  {language}
                </Text>
              </TouchableOpacity>
            ))}
          </View>
          
          <View style={styles.buttonRow}>
            <TouchableOpacity style={styles.secondaryButton} onPress={prevStep}>
              <Text style={styles.buttonText}>上一步</Text>
            </TouchableOpacity>
            <TouchableOpacity 
              style={[styles.primaryButton, languages.length === 0 && styles.disabledButton]} 
              onPress={nextStep}
              disabled={languages.length === 0}
            >
              <Text style={styles.buttonText}>继续</Text>
            </TouchableOpacity>
          </View>
        </View>
      )}

      {/* 步骤7: 选择母语 */}
      {step === 7 && (
        <View style={styles.stepContainer}>
          <Text style={styles.title}>你的母语</Text>
          <Text style={styles.subtitle}>请选择你的母语</Text>
          
          <View style={styles.optionsContainer}>
            {languageOptions.map((language, index) => (
              <TouchableOpacity 
                key={index}
                style={[styles.optionItem, motherTongue === language && styles.selectedOption]}
                onPress={() => selectMotherTongue(language)}
              >
                <Text style={[styles.optionText, motherTongue === language && styles.selectedOptionText]}>
                  {language}
                </Text>
              </TouchableOpacity>
            ))}
          </View>
          
          <View style={styles.buttonRow}>
            <TouchableOpacity style={styles.secondaryButton} onPress={prevStep}>
              <Text style={styles.buttonText}>上一步</Text>
            </TouchableOpacity>
            <TouchableOpacity 
              style={[styles.primaryButton, !motherTongue && styles.disabledButton]} 
              onPress={nextStep}
              disabled={!motherTongue}
            >
              <Text style={styles.buttonText}>继续</Text>
            </TouchableOpacity>
          </View>
        </View>
      )}

      {/* 步骤8: 选择国籍 */}
      {step === 8 && (
        <View style={styles.stepContainer}>
          <Text style={styles.title}>你的国籍</Text>
          <Text style={styles.subtitle}>请选择你的国籍</Text>
          
          <View style={styles.optionsContainer}>
            {nationalities.map((country, index) => (
              <TouchableOpacity 
                key={index}
                style={[styles.optionItem, nationality === country && styles.selectedOption]}
                onPress={() => selectNationality(country)}
              >
                <Text style={[styles.optionText, nationality === country && styles.selectedOptionText]}>
                  {country}
                </Text>
              </TouchableOpacity>
            ))}
          </View>
          
          <View style={styles.buttonRow}>
            <TouchableOpacity style={styles.secondaryButton} onPress={prevStep}>
              <Text style={styles.buttonText}>上一步</Text>
            </TouchableOpacity>
            <TouchableOpacity 
              style={[styles.primaryButton, !nationality && styles.disabledButton]} 
              onPress={nextStep}
              disabled={!nationality}
            >
              <Text style={styles.buttonText}>完成</Text>
            </TouchableOpacity>
          </View>
        </View>
      )}
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 20,
    flexGrow: 1,
    backgroundColor: '#fff',
  },
  progressBarContainer: {
    height: 6,
    backgroundColor: '#eee',
    borderRadius: 3,
    marginBottom: 20,
  },
  progressBar: {
    height: 6,
    backgroundColor: '#e91e63',
    borderRadius: 3,
  },
  stepText: {
    textAlign: 'center',
    marginBottom: 20,
    color: '#666',
  },
  stepContainer: {
    flex: 1,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 10,
    textAlign: 'center',
  },
  subtitle: {
    color: '#999',
    marginBottom: 30,
    textAlign: 'center',
  },
  agreementContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 30,
  },
  checkbox: {
    width: 20,
    height: 20,
    borderWidth: 1,
    borderColor: '#ccc',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 10,
  },
  agreementText: {
    flex: 1,
  },
  primaryButton: {
    backgroundColor: '#e91e63',
    padding: 15,
    borderRadius: 5,
    alignItems: 'center',
    marginTop: 20,
  },
  secondaryButton: {
    backgroundColor: '#ccc',
    padding: 15,
    borderRadius: 5,
    alignItems: 'center',
    marginTop: 20,
    marginRight: 10,
    flex: 1,
  },
  buttonText: {
    color: 'white',
    fontWeight: 'bold',
  },
  disabledButton: {
    backgroundColor: '#f0f0f0',
  },
  imageUploadContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginBottom: 30,
  },
  addImageBox: {
    width: 100,
    height: 100,
    borderWidth: 1,
    borderColor: '#ddd',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 10,
    marginBottom: 10,
  },
  addImageText: {
    fontSize: 30,
    color: '#ccc',
  },
  imageContainer: {
    position: 'relative',
    marginRight: 10,
    marginBottom: 10,
  },
  uploadedImage: {
    width: 100,
    height: 100,
    borderRadius: 5,
  },
  removeImageButton: {
    position: 'absolute',
    top: -5,
    right: -5,
    backgroundColor: 'red',
    width: 20,
    height: 20,
    borderRadius: 10,
    justifyContent: 'center',
    alignItems: 'center',
  },
  removeImageText: {
    color: 'white',
    fontWeight: 'bold',
  },
  buttonRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 20,
  },
  input: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 5,
    padding: 10,
    marginBottom: 15,
  },
  radioContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 15,
  },
  radioLabel: {
    marginRight: 15,
  },
  radioButton: {
    borderWidth: 1,
    borderColor: '#ccc',
    padding: 10,
    marginRight: 10,
    borderRadius: 5,
  },
  selectedRadio: {
    backgroundColor: '#e91e63',
    borderColor: '#e91e63',
  },
  interestsContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginBottom: 30,
  },
  interestItem: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 20,
    paddingVertical: 8,
    paddingHorizontal: 15,
    margin: 5,
  },
  selectedInterest: {
    backgroundColor: '#e91e63',
    borderColor: '#e91e63',
  },
  interestText: {
    color: '#333',
  },
  selectedInterestText: {
    color: 'white',
  },
  optionsContainer: {
    marginBottom: 30,
  },
  optionItem: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 5,
    padding: 15,
    marginBottom: 10,
  },
  selectedOption: {
    backgroundColor: '#e91e63',
    borderColor: '#e91e63',
  },
  optionText: {
    color: '#333',
    textAlign: 'center',
  },
  selectedOptionText: {
    color: 'white',
  },
});

export default CompleteProfileScreen;